﻿using System;
using System.Collections.Generic;
using NCommet.Core.Agents;
using log4net;
using NCommet.Modules.Dao;
using System.Text;
using NHibernate;
using NCommet.Core;

namespace NCommet.Modules.DBSorter
{
    public class DBSorter : ISorter
    {
        private ILog MyLog { get { return LogManager.GetLogger(typeof(DBSorter)); } }


        /// <summary>
        /// Exposes the ISession used within the DAO.
        /// </summary>
        private ISession session
        {
            get
            {
                return NHibernateSessionManager.Instance.GetSession();
            }
        }

        public IEnumerable<Item> Sort(IList<int> ItemsToSort, int Key)
        {
            if (ItemsToSort == null || ItemsToSort.Count <= 0)
                return new List<Item>();

            MyLog.DebugFormat("Sorting {0} ids using by sortKey {1}", ItemsToSort.Count, Key);

            SupportedTypes? stCatalog = DBIndexer.GetSupportedTypeFromCatalog(Key);
            string field = "SortValueStr";
            if (stCatalog.HasValue)
            {
                switch (stCatalog.Value)
                {
                    case SupportedTypes.Int:
                        field = "SortValueInt";
                        break;
                    case SupportedTypes.DateTime:
                        field = "SortValueDate";
                        break;
                }
            }

            StringBuilder sb = new StringBuilder();
            foreach (int i in ItemsToSort)
                sb.Append(i).Append(", ");
            sb.Remove(sb.Length - 2, 2);
            IList<Item> result = session.CreateSQLQuery(
"SELECT {a.*} FROM Item {a} LEFT JOIN " +
"(SELECT * FROM ItemIndex WHERE SortKey=:sortKey) b " +
"ON a.ID=b.ID " +
"WHERE a.ID IN (" + sb.ToString() + ") ORDER BY b." + field).AddEntity("a", typeof(Item)).SetParameter("sortKey", Key).List<Item>();
            MyLog.Debug("Sorting complete");
            return result;
        }

        public IList<int> SortToIds(IList<int> IdsToSort, int Key)
        {
            List<Item> lst = new List<Item>(Sort(IdsToSort, Key));
            return Item.ToIntList(lst);
        }
    }

    
}
